#include "stdafx.h"

const int cHostPort = 58213;

const unsigned cNetChat = 1;

net::INetService* _netService;
bool _connected = false;
bool terminateApp = false;

DWORD _stdcall ThreadInput(void* arg)
{
	while (!terminateApp)
	{
		std::string text;
		std::cin >> text;

		if (net::NetChat::I())
			net::NetChat::I()->PushLine(text);

		//std::stringstream sstream(text);
		//sstream >> net::NetChat::I()->testInt;

		if (text == "exit")
			terminateApp = true;
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	lsl::appLog.fileName = "clientLog.txt";
	lsl::appLog.Clear();

	LSL_LOG("client init");

	__int64 cpuFreq;
	QueryPerformanceFrequency((LARGE_INTEGER*)&cpuFreq);
	__int64 tick;
	QueryPerformanceCounter((LARGE_INTEGER*)&tick);

	net::INetService& netService = net::GetNetService();
	_netService = &netService;
	netService.syncRate(70);
	
	netService.modelClasses().Add<net::NetChat>(cNetChat);	

	LSL_LOG("client starting...");

	netService.Initializate();

	std::string ipAddress = "127.0.0.1";
	while (true)
	{
		//std::cin >> ipAddress;

		if (ipAddress == "ping")
		{
			LSL_LOG("ping started...");

			{
				__int64 newTick;
				QueryPerformanceCounter((LARGE_INTEGER*)&newTick);
				unsigned time = static_cast<unsigned>((newTick - tick) * 1000 / cpuFreq);

				netService.Process(time);
			}

			_netService->Ping(cHostPort, 5000, 1000);
			
			while (!terminateApp && _netService->IsPingProcess())
			{
				Sleep(16);

				__int64 newTick;
				QueryPerformanceCounter((LARGE_INTEGER*)&newTick);
				unsigned time = static_cast<unsigned>((newTick - tick) * 1000 / cpuFreq);

				netService.Process(time);
			}

			LSL_LOG("ping completed.");
		}
		else
			break;
	}	
	
	netService.Connect(net::Endpoint(ipAddress, cHostPort));
	CreateThread(0, 0, &ThreadInput, NULL, 0, 0);

	while (!terminateApp)
	{
		Sleep(16);

		__int64 newTick;
		QueryPerformanceCounter((LARGE_INTEGER*)&newTick);
		unsigned time = static_cast<unsigned>((newTick - tick) * 1000 / cpuFreq);

		netService.Process(time);

		if (!_connected && netService.isConnected())
		{
			LSL_LOG("client start");

			_connected = true;			
		}
		else if (!netService.isConnected())
			continue;		

		if (netService.GetConnection(0)->pingTime() == time)
			LSL_TRACE(lsl::StrFmt("ping %d", netService.GetConnection(0)->ping()));
	}

	netService.Finalizate();

	return 0;
}

